<template>
  <div class="imgUpload">
    <el-divider content-position="left">待上传区</el-divider>
    <div id="ossfile">你的浏览器不支持flash,Silverlight或者HTML5！</div>
    <el-divider content-position="left">上传展示区</el-divider>
    <div id="imgBox">
      <img v-for="item in imgList" :key="item" :src="item" alt="">
    </div>
    <!-- <pre id="tipView"></pre> -->
    <div id="container">
      <el-button id="selectfiles" style="margin-left: 10px;" size="small" type="success">上传图片</el-button>
      <el-button id="postfiles" style="margin-left: 10px;" size="small" type="success">上传到服务器</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="clearUpload">清空队列</el-button>
    </div>
  </div>
</template>

<script>
import plupload from 'plupload'

const serverUrl = process.env.VUE_APP_SERVICE_URL + '/open/oss/policy'
const albbUrl = 'http://oss-cn-hangzhou.aliyuncs.com'
var accessid = ''
// var accesskey = ''
var host = ''
var policyBase64 = ''
var signature = ''
var callbackbody = ''
// var filename = ''
var key = ''
var expire = 0
var g_object_name = ''
var g_object_name_type = ''
var now = Date.parse(new Date()) / 1000
// var timestamp = Date.parse(new Date()) / 1000

function send_request() {
  var xmlhttp = null
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest()
  } else if (window.ActiveXObject) {
    // xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    console.log('ActiveXObject')
  }

  if (xmlhttp != null) {
    // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
    // serverUrl = 'http://88.88.88.88:8888/aliyun-oss-appserver-php/php/get.php'

    xmlhttp.open('GET', serverUrl, false)
    xmlhttp.send(null)
    return xmlhttp.responseText
  } else {
    alert('Your browser does not support XMLHTTP.')
  }
}

function get_signature() {
  // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
  now = Date.parse(new Date()) / 1000
  if (expire < now + 3) {
    const body = send_request()
    var obj = JSON.parse(body)
    host = obj['host']
    policyBase64 = obj['policy']
    accessid = obj['accessKeyId']
    signature = obj['signature']
    expire = parseInt(obj['expire'])
    callbackbody = obj['callback']
    key = obj['dir']
    return true
  }
  return false
}

function random_string(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  pwd = 'T' + pwd + Date.parse(new Date())
  return pwd
}

function get_suffix(filename) {
  const pos = filename.lastIndexOf('.')
  let suffix = ''
  if (pos !== -1) {
    suffix = filename.substring(pos)
  }
  return suffix
}

function calculate_object_name(filename) {
  if (g_object_name_type === 'local_name') {
    g_object_name += '${filename}'
  } else if (g_object_name_type === 'random_name') {
    const suffix = get_suffix(filename)
    g_object_name = key + random_string(10) + suffix
  }
  return ''
}

// function get_uploaded_object_name(filename) {
//   if (g_object_name_type === 'local_name') {
//     let tmp_name = g_object_name
//     tmp_name = tmp_name.replace('${filename}', filename)
//     return tmp_name
//   } else if (g_object_name_type === 'random_name') {
//     return g_object_name
//   }
// }

function set_upload_param(up, filename, ret) {
  if (ret === false) {
    ret = get_signature()
  }
  g_object_name = key
  if (filename !== '') {
    // const suffix = get_suffix(filename)
    calculate_object_name(filename)
  }
  const new_multipart_params = {
    key: g_object_name,
    policy: policyBase64,
    OSSAccessKeyId: accessid,
    success_action_status: '200', // 让服务端返回200,不然，默认会返回204
    callback: callbackbody,
    signature: signature
  }

  up.setOption({
    url: host,
    multipart_params: new_multipart_params
  })

  up.start()
}
export default {
  name: 'UploadImg',
  props: {
  },
  data() {
    return {
      imgList: [],
      uploader: Object
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.initPlUploader()
  },
  methods: {
    /**
     * 初始化上传插件
     */
    initPlUploader() {
      const that = this
      that.uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: 'selectfiles',
        url: albbUrl,

        filters: {
          mime_types: [
            // 只允许上传图片和zip文件
            { title: 'Image files', extensions: 'jpg,gif,png,bmp' },
            { title: 'Zip files', extensions: 'zip,rar,ipa' }
          ],
          max_file_size: '20mb', // 最大只能上传10mb的文件
          prevent_duplicates: true // 不允许选取重复文件
        },

        init: {
          PostInit: function() {
            console.log('PostInit')
            document.getElementById('ossfile').innerHTML = ''
            document.getElementById('postfiles').onclick = function() {
              set_upload_param(that.uploader, '', false)
              return false
            }
          },
          FileFiltered: function(up, file) {
            console.log('FileFiltered', file)
          },
          FilesAdded: function(up, files, responseObject) {
            var reader = new FileReader()
            reader.readAsDataURL(files[0].getNative())
            reader.onload = function(e) {
              var image = new Image()
              image.src = e.target.result
              image.onload = function() {
                if (this.width !== 1024 || this.height !== 1024) {
                  console.log('尺寸不符')
                  return
                }
              }
            }
            plupload.each(files, function(file) {
              document.getElementById('ossfile').innerHTML +=
                      '<div id="' +
                      file.id +
                      '">' +
                      file.name +
                      ' (' +
                      plupload.formatSize(file.size) +
                      ')<b style="margin-left:20px;color:green;"></b>' + '</div>'
                      // '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
                      // '</div>'
            })
          },

          BeforeUpload: function(up, file) {
            console.log('BeforeUpload', file)
            g_object_name_type = 'random_name'
            set_upload_param(up, file.name, true)
          },

          UploadProgress: function(up, file) {
            console.log('UploadProgress', file)
            var d = document.getElementById(file.id)
            d.getElementsByTagName('b')[0].innerHTML =
                    '<span>' + file.percent + '%</span>'
            // var prog = d.getElementsByTagName('div')[0]
            // var progBar = prog.getElementsByTagName('div')[0]
            // progBar.style.width = 2 * file.percent + 'px'
            // progBar.setAttribute('aria-valuenow', file.percent)
          },

          FileUploaded: function(up, file, info) {
            console.log('===============================')
            console.log('FileUploaded')
            if (info.status === 200) {
              // document
              //   .getElementById(file.id)
              //   .getElementsByTagName('b')[0].innerHTML =
              //         'upload to oss success, object name:' +
              //         get_uploaded_object_name(file.name) +
              //         ' 回调服务器返回的内容是:' +
              //         info.response
              var resA = JSON.parse(info.response)
              that.$emit('imgInfo', resA.data)
              that.imgList.push(resA.data.filename)
            } else if (info.status === 203) {
              document
                .getElementById(file.id)
                .getElementsByTagName('b')[0].innerHTML =
                      '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' +
                      info.response
            } else {
              document
                .getElementById(file.id)
                .getElementsByTagName('b')[0].innerHTML = info.response
            }
          },

          Error: function(up, err) {
            if (err.code === -600) {
              that.msgError('选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小')
              // document
              //   .getElementById('tipView')
              //   .appendChild(
              //     document.createTextNode(
              //       '\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小'
              //     )
              //   )
            } else if (err.code === -601) {
              that.msgError('选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型')
              // document
              //   .getElementById('tipView')
              //   .appendChild(
              //     document.createTextNode(
              //       '\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型'
              //     )
              //   )
            } else if (err.code === -602) {
              that.msgError('这个文件已经上传过一遍了')
              // document
              //   .getElementById('tipView')
              //   .appendChild(
              //     document.createTextNode('\n')
              //   )
            } else {
              that.msgError('Error xml:' + err.response)
              // document
              //   .getElementById('tipView')
              //   .appendChild(
              //     document.createTextNode('\nError xml:' + err.response)
              //   )
            }
          }
        }
      })
      that.uploader.init()
    },
    // 重置数据队列
    clearUpload() {
      document.getElementById('ossfile').innerHTML = ''
      this.imgList = []
      this.uploader.splice()
    }
  }
}
</script>

<style lang="scss" scoped>
#ossfile, #imgBox{
  width: 90%;
  min-height: 180px;
  border: 1px solid black;
  border-radius: 6px;
  margin: 10px 0 10px 20px;
  padding: 10px;
}
#ossfile{
  min-height: 80px;
}
#imgBox>img{
  width:160px;
  height: 160px;
  display:inline-block;
  margin-left: 18px;
  border: 1px dashed #ccc;
  border-radius: 9px;
}
#container{
  text-align: right;
  padding: 20px 100px 0 0;
}
</style>
